﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Chat.Business.Service.BasicHttp;
using Chat.Business.Service.NetP2P;
using VMuktiService;
using Chat.Business.Service.DataContracts;
using System.ServiceModel;
using System.IO;
using VMuktiAPI;
using System.Runtime.InteropServices;

namespace Chat.Presentation
{
    /// <summary>
    /// Interaction logic for ctlChat.xaml
    /// </summary>
    /// 

    public enum ModulePermissions
    {
        Add = 0,
        Edit = 1,
        Delete = 2,
        View = 3
    }

    public partial class ctlChat : UserControl,IDisposable
    {
        object objNetTcpChat = new clsNetTcpChat();
        INetTcpChatChannel channelNetTcp;
        IHttpChat channelHttp;

        System.Windows.Threading.DispatcherTimer dispTimer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Normal);

        object objHttpChat = new clsHttpChat();

        List<clsMessage> lstMessage = new List<clsMessage>();

        System.Threading.Thread tHostChat = null;

        public delegate void DelSendMessage(List<object> lstMsg);
        public DelSendMessage objDelSendMsg;

        int temp = 0;
        int tempcounter = 0;
      
        public delegate void DelDisplayName(string lstUserName);
        public DelDisplayName objDelDisplayName;

        public delegate void DelSignOutMessage(List<object> lstMsg);
        public DelSignOutMessage objDelSignOutMsg;

        public delegate void DelGetMessage();
        public DelGetMessage objDelGetMsg;

        public delegate void DelSendPeerMessage(string Msg);
        public DelSendPeerMessage objDelSendPeerMsg;

        public delegate void DelGetUserList();
        public DelGetUserList objDelGetUserList;

        public string strUri;

        ModulePermissions[] modPer;

        
        byte[] arr = new byte[5000];
       

        List<string> lstName = new List<string>();

        public string strRole = "";
        StringBuilder sb1 = CreateTressInfo();

        #region Win32

        [DllImport("user32.dll")]
        static extern bool FlashWindow(IntPtr hwnd, bool bInvert);

        [DllImport("Kernel32.dll")]
        static extern bool Beep(uint dwFreq, uint dwDuration);

        [DllImport("user32.dll")]
        static extern bool FlashWindowEx(IntPtr hWnd);

        #endregion

        public ctlChat(VMuktiAPI.PeerType PeerType, string uri, ModulePermissions[] MyPermissions,string Role)
        {
            try
            {
                InitializeComponent();
                
                this.Unloaded += new RoutedEventHandler(ctlChat_Unloaded);
                txtChat.KeyDown += new KeyEventHandler(txtChat_KeyDown);
                objDelDisplayName = new DelDisplayName(DisplayName);

                VMuktiAPI.VMuktiHelper.RegisterEvent("SignOut").VMuktiEvent += new VMuktiAPI.VMuktiEvents.VMuktiEventHandler(ctlChat_VMuktiEvent);

                Application.Current.Exit += new ExitEventHandler(Current_Exit);

                modPer = MyPermissions;
                objDelSendMsg = new DelSendMessage(delSendMessage);
                objDelSignOutMsg = new DelSignOutMessage(delSignoutMessage);
                objDelGetMsg = new DelGetMessage(delGetMessage);
                objDelSendPeerMsg = new DelSendPeerMessage(delSendPeerMessage);
                objDelGetUserList = new DelGetUserList(delGetUserList);
                strRole = Role;

                tHostChat = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(hostchatservice));
                List<object> lstParams = new List<object>();
                lstParams.Add(PeerType);
                lstParams.Add(uri);
                lstParams.Add(MyPermissions);


                StringBuilder sb = new StringBuilder();
                sb.Append("Loading Chat Module");
                sb.AppendLine(sb1.ToString());
                //sb.AppendLine();
                //sb.Append("User Is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                //sb.AppendLine();
                //sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
                //sb.AppendLine();
                //sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                //sb.AppendLine();
                //sb.Append("User's Machine Ip Address : " + VMuktiAPI.GetIPAddress.ClsGetIP4Address.GetIP4Address());
                //sb.AppendLine("----------------------------------------------------------------------------");
                VMuktiAPI.ClsLogging.WriteToTresslog(sb);
                tHostChat.Start(lstParams);              
                
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "ctlChat()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
                //MessageBox.Show("ctlchat" + exp.Message);
            }
        }

        void Current_Exit(object sender, ExitEventArgs e)
        {
            try
            {
                if (dispTimer != null)
                {
                    dispTimer.Stop();
                }                
                if (channelHttp != null)
                {
                    channelHttp = null;
                }
                if (channelNetTcp != null && channelNetTcp.State == CommunicationState.Opened)
                {
                    channelNetTcp = null;
                }
                VMuktiAPI.VMuktiHelper.UnRegisterEvent("SignOut");
            }
            catch(Exception exp)
            {
                exp.Data.Add("My Key", "Current_Exit()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
                //MessageBox.Show("Current_Exit " + exp.Message);
            }
        }

        public void ctlChat_VMuktiEvent(object sender, VMuktiAPI.VMuktiEventArgs e)
        {
            ClosePod();
        }       

        void txtChat_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {                 
                    btnChat_Click(null, null);
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "txtChat_KeyDown()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
                //MessageBox.Show("txtChat_KeyDown " + exp.Message);
            }
        }

        void ctlChat_Unloaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //if (dispTimer != null)
                //{
                //    dispTimer.Stop();
                //}

                //if (channelHttp != null)
                //{
                //    channelHttp = null;
                //}
                //if (channelNetTcp != null && channelNetTcp.State == CommunicationState.Opened)
                //{
                //    channelNetTcp = null;
                //}
            }
            catch (Exception exp)
            {
                //System.Diagnostics.EventLog el = new System.Diagnostics.EventLog("Application", Environment.MachineName);
                //el.WriteEntry("ctlChat_Unloaded " + exp.Message);
                //el.Close();
				exp.Data.Add("My Key", "ctlChat_Unloaded()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
               
               // MessageBox.Show("ctlChat_Unloaded " + exp.Message);
            }
        }

        public void hostchatservice(object lstParams)
        {
            List<object> lstTempObj = (List<object>)lstParams;
            strUri = lstTempObj[1].ToString();     
            try
            {
                if ((VMuktiAPI.PeerType)lstTempObj[0] == VMuktiAPI.PeerType.NodeWithNetP2P || (VMuktiAPI.PeerType)lstTempObj[0] == VMuktiAPI.PeerType.BootStrap || (VMuktiAPI.PeerType)lstTempObj[0] == VMuktiAPI.PeerType.SuperNode)
                {
                    NetPeerClient npcChat = new NetPeerClient();
                    ((clsNetTcpChat)objNetTcpChat).EntsvcJoin += new clsNetTcpChat.delsvcJoin(wndChat_EntsvcJoin);
                    ((clsNetTcpChat)objNetTcpChat).EntsvcSendMessage += new clsNetTcpChat.delsvcSendMessage(wndChat_EntsvcSendMessage);
                    ((clsNetTcpChat)objNetTcpChat).EntsvcGetUserList += new clsNetTcpChat.delsvcGetUserList(ctlChat_EntsvcGetUserList);
                    ((clsNetTcpChat)objNetTcpChat).EntsvcSetUserList += new clsNetTcpChat.delsvcSetUserList(ctlChat_EntsvcSetUserList);
                    ((clsNetTcpChat)objNetTcpChat).EntsvcSignOutChat += new clsNetTcpChat.delsvcSignOutChat(ctlChat_EntsvcSignOutChat);
                    ((clsNetTcpChat)objNetTcpChat).EntsvcUnJoin += new clsNetTcpChat.delsvcUnJoin(wndChat_EntsvcUnJoin);
                    //MessageBox.Show(strUri);
                    channelNetTcp = (INetTcpChatChannel)npcChat.OpenClient<INetTcpChatChannel>(strUri, strUri.ToString().Split(':')[2].Split('/')[1], ref objNetTcpChat);
                    //MessageBox.Show("client opened");
                    while (temp < 20)
                    {
                        try
                        {
                            channelNetTcp.svcJoin(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                            //MessageBox.Show("svcjoin called");
                            temp = 20;
                            //this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelGetUserList);
                            channelNetTcp.svcGetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                        }
                        catch
                        {
                            temp++;
                            System.Threading.Thread.Sleep(1000);
                        }
                        
                    }
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Chat Module:Opened Chat P2P Client");
                    sb.AppendLine();
                  
                    //sb.Append("User Is (From) : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                    //sb.AppendLine();
                    //sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
                    //sb.AppendLine();
                    //sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                    //sb.AppendLine();
                    sb.Append("Uri for opening the client is : " + strUri);
                    sb.AppendLine();
                    sb.Append("MeshId for opening the client is : " + strUri.ToString().Split(':')[2].Split('/')[1]);
                    sb.AppendLine();
                    sb.AppendLine(sb1.ToString());
                    VMuktiAPI.ClsLogging.WriteToTresslog(sb);

                }
                else
                {
                    //DummyClient dc = new DummyClient(VMukti.Global.VMuktiGlobal.strUserName);
                    //string httpuri = dc.ChatClient(idCounter, strUri, VMukti.Global.VMuktiGlobal.strSuperNodeIP);

                    BasicHttpClient bhcChat = new BasicHttpClient();
                    channelHttp = (IHttpChat)bhcChat.OpenClient<IHttpChat>(strUri);

                    while (tempcounter < 20)
                    {
                        try
                        {
                            channelHttp.svcJoin(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                            tempcounter = 20;
                            //this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelGetUserList);
                            channelHttp.svcGetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                            btnChat.IsEnabled = true;
                            txtChat.IsEnabled = true;
                        }
                        catch
                        {
                            tempcounter++;
                            System.Threading.Thread.Sleep(1000);
                        }
                    }

                    dispTimer.Interval = TimeSpan.FromSeconds(2);
                    dispTimer.Tick += new EventHandler(dispTimer_Tick);
                    dispTimer.Start();
                    StringBuilder sb = new StringBuilder();
                    sb.Append("chat module: Opened Http Chat Client with Timers");
                    sb.AppendLine();
                   
                    //sb.Append("User Is (From) : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                    //sb.AppendLine();
                    //sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
                    //sb.AppendLine();
                    //sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                    //sb.AppendLine();
                    sb.Append("Uri for opening the client is : " + strUri);
                    sb.AppendLine();
                    sb.AppendLine(sb1.ToString());
                    ClsLogging.WriteToTresslog(sb);
                }
            }
            catch (Exception exp)
            {  
				//MessageBox.Show("hostchatservice" + exp.Message);
				//if (exp.InnerException != null)
				//{
				//    MessageBox.Show("hostchatservice" + exp.InnerException.Message);
				//}
				exp.Data.Add("My Key", "hostchatservice()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
            }
        }      

        void btnChat_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                rtbChat.AppendText(Char.ConvertFromUtf32(13) + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName + " Says : " + txtChat.Text);
                rtbChat.ScrollToEnd();
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objDelSendPeerMsg, txtChat.Text);
                StringBuilder sb = new StringBuilder();
                sb.Append("Chat Module: Chat Send Button Clicked");
                sb.AppendLine();
                //sb.Append("User Is (From) : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                //sb.AppendLine();
                //sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
                //sb.AppendLine();
                //sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                //sb.AppendLine();
                sb.Append("Msg is : " + txtChat.Text);
                sb.AppendLine();
                sb.AppendLine("Receiver's Name : ");

                for (int i = 0; i < lstName.Count; i++)
                {
                    sb.AppendLine(lstName[i]);
                }
                sb.AppendLine(sb1.ToString());
                ClsLogging.WriteToTresslog(sb);
                txtChat.Text = "";
            }
            catch (Exception exp)
            {  
                //MessageBox.Show(exp.Message);
				exp.Data.Add("My Key", "btnChat_Click()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
            }
        }

        void dispTimer_Tick(object sender, EventArgs e)
        {            
            try
            {
                ((System.Windows.Threading.DispatcherTimer)sender).Stop();
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,objDelGetMsg);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "DispTimer_Tick()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }     

        public void BuddySelected(List<string> lstTag)
		{
			try
			{
				this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelDisplayName, lstTag[0]);
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "BuddySelected()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        public void ClosePod()
		{
			try
			{
				//call unjoin method
                
				if (channelNetTcp != null)
				{
					channelNetTcp.svcSignOutChat(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, lstName);
				}
				else if (channelHttp != null)
				{
					channelHttp.svcSignOutChat(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, lstName);
				}

				if (channelNetTcp != null)
				{
					channelNetTcp = null;
				}
				if (channelHttp != null)
				{
					channelHttp = null;
				}
                if (dispTimer != null)
                {
                    dispTimer.Stop();
                }

                Dispose();
			}
			catch (Exception exp)
			{

				exp.Data.Add("My Key", "ClosePod()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        public void delSendPeerMessage(string msg)
        {
            if (VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.NodeWithNetP2P || VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.SuperNode || VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType == VMuktiAPI.PeerType.BootStrap)
            {
                if (channelNetTcp != null)
                {
                    channelNetTcp.svcSendMessage(msg, VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, lstName);
                }
            }
            else
            {
                if (channelHttp != null)
                {
                    channelHttp.svcSendMessage(msg, VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName, lstName);
                }
            }
        }

        public void delGetUserList()
        {
            try
            {
                if (channelNetTcp != null)
                {
                    channelNetTcp.svcGetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                    btnChat.IsEnabled = true;
                    txtChat.IsEnabled = true;
                }
                if (channelHttp != null)
                {
                    channelHttp.svcGetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                    btnChat.IsEnabled = true;
                    txtChat.IsEnabled = true;
                }
                //MessageBox.Show("getulist called");
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "delGetUserList()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        #region Nettcp events

        void wndChat_EntsvcJoin(string uName)
        {

        }

        void wndChat_EntsvcSendMessage(string msg, string from, List<string> to)
		{
			try
			{
				if (from != VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
				{
					List<object> lstStr = new List<object>();
					lstStr.Add(from);
					lstStr.Add(msg);
					lstStr.Add(to);
					this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelSendMsg, lstStr);
				}
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "wndChat_EntsvcSendMessage()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        void ctlChat_EntsvcSetUserList(string uName)
		{
			try
			{
				if (uName != VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
				{
					this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelDisplayName, uName);
				}
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "ctlChat_EntsvcSetUserList()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        void ctlChat_EntsvcGetUserList(string uName)
        {
            try
            {
                //MessageBox.Show("1");
                if (uName != VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
                {
                    //MessageBox.Show("2");
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelDisplayName, uName);
                    //MessageBox.Show("3");
                    if (channelNetTcp != null)
                    {
                        //MessageBox.Show("4");
                        channelNetTcp.svcSetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                        //MessageBox.Show("5");
                    }

                    if(channelHttp!=null)
                    {
                        channelHttp.svcSetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                    }
                }
            }
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "ctlChat_EntsvcGetUserList()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        void ctlChat_EntsvcSignOutChat(string from, List<string> to)
		{
			try
			{
				if (from != VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
				{
					List<object> lstStr = new List<object>();
					lstStr.Add(from);
					lstStr.Add(to);
					this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelSignOutMsg, lstStr);
				}
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "ctlChat_EntsvcSignOutChat()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        void wndChat_EntsvcUnJoin(string uName)
        {
            
        }

        void delSendMessage(List<object> lstStr)
		{
			try
			{
				List<string> tempArray = (List<string>)lstStr[2];
				// tempArray = tempArray[0].Split(',');
				for (int i = 0; i < tempArray.Count; i++)
				{
					if (tempArray[i] == VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
					{                       
						rtbChat.AppendText(char.ConvertFromUtf32(13) + lstStr[0].ToString() + " says : " + lstStr[1].ToString());
						rtbChat.ScrollToEnd();
                        Beep(800, 150);
                        StringBuilder sb = new StringBuilder();
                        sb.Append("chat Module: Message Received ");
                        sb.AppendLine();
                        //sb.Append("User Is (Receiver) : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                        //sb.AppendLine();
                        //sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
                        //sb.AppendLine();
                        //sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                        //sb.AppendLine();
                        sb.Append("Msg is : " + lstStr[1].ToString());
                        sb.AppendLine();
                        sb.Append("Sender is : " + lstStr[0].ToString());
                        sb.Append("Time is : " + DateTime.Now.ToString());
                        sb.AppendLine(sb1.ToString());
                        ClsLogging.WriteToTresslog(sb);
					}
				}
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "delSendMessage()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        void delSignoutMessage(List<object> lstStr)
		{
            try
            {
                //MessageBox.Show("VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);

                List<string> tempArray = (List<string>)lstStr[1];

                //MessageBox.Show("Inside Dispatcher" + tempArray.Count.ToString());

                //for (int i = 0; i < tempArray.Count; i++)
                //{
                //MessageBox.Show("tempArray[i]" + tempArray[i]);
                //if (tempArray[i] == VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
                //{
                //MessageBox.Show("Sign Out" + lstStr[0]);
                rtbChat.AppendText(char.ConvertFromUtf32(13) + lstStr[0].ToString() + " has left the chat at " + "[" + DateTime.Now.ToString() + "]");
                rtbChat.ScrollToEnd();
                lstName.Remove(lstStr[0].ToString());
                lblDisplay.Content = lblDisplay.Content.ToString().Replace(lstStr[0].ToString(), "").Replace(",,", ",");
                Beep(800, 150);
                StringBuilder sb = new StringBuilder();
                sb.Append("Chat Module: Buddy Leaving Chat ");
                sb.AppendLine();
                //sb.Append("User Is (Receiver) : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                //sb.AppendLine();
                //sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
                //sb.AppendLine();
                //sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                //sb.AppendLine();
                sb.Append("Sender is (Buddy Leaving Chat): " + lstStr[0].ToString());
                sb.Append("Time is : " + DateTime.Now.ToString());
                sb.AppendLine(sb1.ToString());
                ClsLogging.WriteToTresslog(sb);

                //}
                //}
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "delSignoutMessage()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        public void DisplayName(string lstUserName)
        {
			try
			{
				bool flag = true;
				for (int i = 0; i < lstName.Count; i++)
				{
					if (lstName[i] == lstUserName)
					{
						flag = false;
						break;
					}
				}

				if (flag)
				{
					lstName.Add(lstUserName);
					if (lstUserName != null || lstUserName != "")
					{
						if (lblDisplay.Content != null && lblDisplay.Content.ToString() != "")
						{
							lblDisplay.Content += "  " + lstUserName;
						}
						else
						{
							lblDisplay.Content = lstUserName;
						}
					}
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Chat Module: Buddy To Be Added In the Buddylist");
                    sb.AppendLine();
                    sb.Append("Msg is : " + txtChat.Text);
                    sb.AppendLine();
                    sb.AppendLine("Receiver's Name : ");
                    sb.AppendLine(sb1.ToString());
                    ClsLogging.WriteToTresslog(sb);
				}
               
                Beep(800, 150);
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "DisplayName()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

		void delCloseChat(string from)
		{
			try
			{
				rtbChat.AppendText(Char.ConvertFromUtf32(13) + from + " has left the chat at " + "[" + DateTime.Now.ToString() + "]");
				rtbChat.ScrollToEnd();
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "delCloseChat()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
		}

        void delGetMessage()
        {
            try
            {
                List<clsMessage> myMessages = channelHttp.svcGetMessages(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                if (myMessages != null)
                {
                    for (int i = 0; i < myMessages.Count; i++)
                    {
                        if (myMessages[i].strMessage == "SignOut")
                        {
                            //MessageBox.Show(" TIMER TICK myMessages[i].strFrom  " + myMessages[i].strFrom);
                            //MessageBox.Show(" TIMER TICK VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName  " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                            if (myMessages[i].strFrom != VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
                            {
                                //MessageBox.Show("1");
                                List<object> lstStr = new List<object>();
                                lstStr.Add(myMessages[i].strFrom);
                                lstStr.Add(myMessages[i].lstTo);
                                //for (int lstcnt = 0; lstcnt < myMessages[i].lstTo.Count; lstcnt++)
                                //{
                                //    MessageBox.Show("TIMER TICK TO" + lstcnt + "=" + myMessages[i].lstTo[lstcnt]);

                                //}
                                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelSignOutMsg, lstStr);
                            }
                        }
                        else if (myMessages[i].strMessage == "GetUserList")
                        {
                            try
                            {
                                if (myMessages[i].strFrom != VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
                                {
                                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelDisplayName, myMessages[i].strFrom);
                                    if (channelNetTcp != null)
                                    {
                                        channelNetTcp.svcSetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                                    }

                                    else
                                    {
                                        channelHttp.svcSetUserList(VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                                    }
                                }
                            }
                            catch (Exception exp)
                            {
                                exp.Data.Add("My Key", "delGetMessage1()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
                                ClsException.LogError(exp);
                                ClsException.WriteToErrorLogFile(exp);
                            }
                        }
                        else if (myMessages[i].strMessage == "SetUserList")
                        {
                            if (myMessages[i].strFrom != VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName)
                            {
                                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objDelDisplayName, myMessages[i].strFrom);
                            }
                        }

                        else
                        {
                            rtbChat.AppendText(Char.ConvertFromUtf32(13) + myMessages[i].strFrom + " says: " + myMessages[i].strMessage);
                            rtbChat.ScrollToEnd();
                        }
                    }
                }
                
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "delGetMessage2()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
            this.dispTimer.Start();
        }

        #endregion        
    
        #region IDisposable Members

        public void Dispose()
        {
            //MessageBox.Show("Dispose of chat called");
			try
			{		
                
				if (channelHttp != null)
				{
					channelHttp = null;
				}
				if (channelNetTcp != null)
				{
					channelNetTcp = null;
				}
                GC.Collect();
                GC.WaitForPendingFinalizers();
                //GC.SuppressFinalize(this);
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "Dispose()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        ~ctlChat()
        {
            //MessageBox.Show("destructor of chat called");
			try
			{
               
				if (channelHttp != null)
				{
					channelHttp = null;
				}
				if (channelNetTcp != null)
				{
					channelNetTcp = null;
				}
                
                GC.SuppressFinalize(this);
			}
			catch (Exception exp)
			{
				exp.Data.Add("My Key", "~ctlChat()--:--ctlChat.xaml.cs--:--" + exp.Message + " :--:--");
				ClsException.LogError(exp);
				ClsException.WriteToErrorLogFile(exp);
			}
        }

        #endregion

        #region logging function

        public static StringBuilder CreateTressInfo()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("User Is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
            sb.AppendLine();
            sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
            sb.AppendLine();
            sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
            sb.AppendLine();
            sb.Append("User's Machine Ip Address : " + VMuktiAPI.GetIPAddress.ClsGetIP4Address.GetIP4Address());
            sb.AppendLine("---------------------------------------------------------------------------------------------");
            return sb;
        }

        #endregion
    }
}
